package com.sywb.chuangyebao.library.player;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.sywb.chuangyebao.library.R;
import com.sywb.chuangyebao.library.player.listener.OnPlayerListener;
import com.tencent.rtmp.ITXVodPlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.TXVodPlayConfig;
import com.tencent.rtmp.TXVodPlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;

import org.bining.footstone.log.Logger;
import org.bining.footstone.utils.ApkUtils;
import org.bining.footstone.utils.FileUtils;
import org.bining.footstone.utils.NetUtils;
import org.bining.footstone.utils.ScreenUtils;

/**
 * 腾讯云播放
 * https://cloud.tencent.com/document/product/454/12148
 */
public class TXPlayerView extends FrameLayout implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, ITXVodPlayListener, IVideoController {

    private FrameLayout llContainer;

    private ImageView ivPreview;

    private LinearLayout llPlayer;
    private ImageView ivPlayer;

    public TextView tvDuration;

    public TextView tvReset;

    public LinearLayout llShare;
    public TextView tvShareWechat;
    public TextView tvShareFriend;
    public TextView tvShareQQ;
    public TextView tvShareSpace;

    public LinearLayout llErrorView;
    public TextView tvErrorMsg;
    public TextView tvErrorBtn;

    private LinearLayout llLoading;

    private LinearLayout llTools;
    private TextView tvCurrentPosition;
    private SeekBar sbProgress;
    private TextView tvTotalDuration;
    private ImageView ivFullScreen;

    private ProgressBar pbProgress;

    private Context mContext;
    private TXCloudVideoView txCloudVideoView;
    private TXVodPlayer txVodPlayer;

    private String playerUrl;

    private int mPlayMode;//视频模式 MODE_VIDEO:点播 MODE_LIVE:直播
    private int mPlayerState;// 视频状态 0:准备播放 1:正在播放 2:暂停播放 4:播放错误 5:播放完成

    private boolean isCanReplay;// 记录视频播放完成后是否可以重播
    private boolean mAutoPlayerState = false;// 记录由系统触发AutoPause时播放器是否在播放

    private CountDownTimer mCountDownTimer;

    private OnPlayerListener onPlayerListener;

    public TXPlayerView(Context context) {
        this(context, null);
    }

    public TXPlayerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @SuppressLint("WrongConstant")
    public TXPlayerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        inflate(context, R.layout.layout_video_player, this);

        mContext = context;

        this.llContainer = findViewById(R.id.ll_container);
        this.ivPreview = findViewById(R.id.iv_preview);

        this.llPlayer = findViewById(R.id.ll_player);
        this.ivPlayer = findViewById(R.id.iv_player);

        this.tvDuration = findViewById(R.id.tv_duration);

        this.tvReset = findViewById(R.id.tv_reset);

        this.llShare = findViewById(R.id.ll_share);
        this.tvShareWechat = findViewById(R.id.tv_share_wechat);
        this.tvShareFriend = findViewById(R.id.tv_share_friend);
        this.tvShareQQ = findViewById(R.id.tv_share_qq);
        this.tvShareSpace = findViewById(R.id.tv_share_space);

        this.llErrorView = findViewById(R.id.ll_error_view);
        this.tvErrorMsg = findViewById(R.id.tv_error_msg);
        this.tvErrorBtn = findViewById(R.id.tv_error_btn);

        this.llLoading = findViewById(R.id.ll_loading);

        this.llTools = findViewById(R.id.ll_tools);
        this.tvCurrentPosition = findViewById(R.id.tv_current_position);
        this.sbProgress = findViewById(R.id.sb_progress);
        this.tvTotalDuration = findViewById(R.id.tv_total_duration);
        this.ivFullScreen = findViewById(R.id.iv_full_screen);

        this.pbProgress = findViewById(R.id.pb_progress);

        llContainer.setOnClickListener(this);
        ivPlayer.setOnClickListener(this);
        tvReset.setOnClickListener(this);
        tvShareWechat.setOnClickListener(this);
        tvShareFriend.setOnClickListener(this);
        tvShareQQ.setOnClickListener(this);
        tvShareSpace.setOnClickListener(this);
        tvErrorBtn.setOnClickListener(this);
        ivFullScreen.setOnClickListener(this);
        sbProgress.setOnSeekBarChangeListener(this);

        changeContainerViewSize(((Activity) mContext).getRequestedOrientation() == Configuration.ORIENTATION_LANDSCAPE);

        initVodPlayer();
    }

    /**
     * 根据屏幕方向改变视频容器的大小
     */
    public void changeContainerViewSize(boolean isHorizontalScreen) {
        ViewGroup.LayoutParams layoutParams = llContainer.getLayoutParams();
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        int screenWidth = ScreenUtils.getScreenWidth();
        if (isHorizontalScreen) {// 横屏
            //隐藏状态栏
            ((Activity) mContext).getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            llContainer.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);

            ivFullScreen.setImageResource(R.drawable.small_screen);

            layoutParams.height = screenWidth;
        } else {// 竖屏
            //显示状态栏
            ((Activity) mContext).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            llContainer.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);

            ivFullScreen.setImageResource(R.drawable.full_screen);

            layoutParams.height = (int) (screenWidth * 0.56F);
        }
        llContainer.setLayoutParams(layoutParams);
    }

    /**
     * 初始化播放器
     */
    private void initVodPlayer() {
        if (llContainer.getChildCount() > 0) {
            llContainer.removeAllViews();
        }
        txCloudVideoView = new TXCloudVideoView(mContext);
        llContainer.addView(txCloudVideoView, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        txVodPlayer = new TXVodPlayer(mContext);
        txVodPlayer.setPlayerView(txCloudVideoView);

        if (ApkUtils.lacksPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            TXVodPlayConfig mConfig = new TXVodPlayConfig();
            // 设置本地视频缓存目录
            mConfig.setCacheFolderPath(FileUtils.getAppSdPath(FileUtils.PATH_VIDEO));
            // 设置本地最大缓存文件个数
            mConfig.setMaxCacheItems(20);
            txVodPlayer.setConfig(mConfig);
        }

        // 设置视频图像模式 RENDER_MODE_FILL_SCREEN:等比例铺满 RENDER_MODE_ADJUST_RESOLUTION:等比例缩放来适配最长边
        txVodPlayer.setRenderMode(TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION);
        // 设置视频图像角度 RENDER_ROTATION_PORTRAIT:正常播放 RENDER_ROTATION_LANDSCAPE:画面顺时针旋转270度
        txVodPlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT);
        // 设置倍速播放
        // txVodPlayer.setRate(1.2F);

        txVodPlayer.setVodListener(this);
    }

    /**
     * 播放控制
     */
    public void playControl() {
        // 调整进度
        txVodPlayer.seek(sbProgress.getProgress());
        // 暂停播放
        txVodPlayer.pause();
        // 恢复播放
        txVodPlayer.resume();
    }

    /**
     * 播放结束
     */
    public void playEnd() {
        txVodPlayer.stopPlay(true); // true代表清除最后一帧画面
        txCloudVideoView.onDestroy();
    }

    /**
     * 屏幕截图
     */
    public void snapshot(TXLivePlayer.ITXSnapshotListener itxSnapshotListene) {
        txVodPlayer.snapshot(itxSnapshotListene);
    }

    /**
     * 预加载
     */
    public void preloading() {
        // 播放视频A: 如果将 autoPlay 设置为 true， 那么 startPlay 调用会立刻开始视频的加载和播放
        String urlA = "http://1252463788.vod2.myqcloud.com/xxxxx/v.f10.mp4";
        txVodPlayer.setAutoPlay(true);
        txVodPlayer.startPlay(urlA);

        // 在播放视频 A 的同时，预加载视频 B，做法是将 true 设置为 false
        // String urlB = "http://1252463788.vod2.myqcloud.com/xxxxx/v.f20.mp4";
        // playerB.setAutoPlay(false);
        // playerB.startPlay(urlB); // 不会立刻开始播放，而只会开始加载视频

        // 在视频 A 播放结束的时候，直接启动视频 B 的播放，可以做到无缝切换
        // if (event == TXLiveConstants.PLAY_EVT_PLAY_END) {
        // playerA.stop();
        // playerB.setPlayerView(mPlayerView);
        // playerB.resume();
        // }
    }

    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.ll_container) {
            // 视频容器被点击,若当前在播放则显示播放器工具栏
            if (mPlayerState == 1) {
                showToolsView();
            }
        } else if (i == R.id.iv_player) {
            // 播放按钮被点击,若当前是停止状态则播放视频，在播放则暂停
            switch (mPlayerState) {
                case 1:
                    pause();
                    break;
                case 2:
                    resume();
                    break;
                default:
                    start();
                    break;
            }
        } else if (i == R.id.tv_error_btn) {
            int sceneCode = (int) tvErrorBtn.getTag();
            switch (sceneCode) {
                case 3:
                    if (!NetUtils.isConnected()) {
                        ApkUtils.openNetSetting(mContext);
                    } else {
                        isCanReplay = true;
                        start();
                    }
                    break;
                case 4:
                    PlayerUtils.setUseTrafficPlay(true);
                    if (mPlayerState == 2) {
                        resume();
                    } else {
                        start();
                    }
                    break;
                default:
                    isCanReplay = true;
                    start();
                    break;
            }
        } else if (i == R.id.tv_reset) {
            isCanReplay = true;
            start();
        } else if (i == R.id.tv_share_wechat) {
            if (onPlayerListener != null) {
                onPlayerListener.onShare(1);
            }
        } else if (i == R.id.tv_share_friend) {
            if (onPlayerListener != null) {
                onPlayerListener.onShare(2);
            }
        } else if (i == R.id.tv_share_qq) {
            if (onPlayerListener != null) {
                onPlayerListener.onShare(3);
            }
        } else if (i == R.id.tv_share_space) {
            if (onPlayerListener != null) {
                onPlayerListener.onShare(4);
            }
        } else if (i == R.id.iv_full_screen) {
            // 全屏按钮被点击,放大到全屏
            if (onPlayerListener != null) {
                onPlayerListener.onClickScreenDirection();
            }
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        seekTo(seekBar.getProgress());
        resume();
    }

    @Override
    public void onPlayEvent(TXVodPlayer txVodPlayer, int i, Bundle bundle) {
        switch (i) {
            case TXLiveConstants.PLAY_EVT_CONNECT_SUCC:
                Logger.e("已经连接服务器");
                setLoadingView();
                break;
            case TXLiveConstants.PLAY_EVT_RTMP_STREAM_BEGIN:
                Logger.e("已经连接服务器，开始拉流（仅播放RTMP地址时会抛送）");
                break;
            case TXLiveConstants.PLAY_EVT_RCV_FIRST_I_FRAME:
                Logger.e("网络接收到首个可渲染的视频数据包(IDR)");
                break;
            case TXLiveConstants.PLAY_EVT_PLAY_BEGIN:
                Logger.e("视频播放开始，如果有转菊花什么的这个时候该停了");
                setStartedView();
                showToolsView();
                break;
            case TXLiveConstants.PLAY_EVT_PLAY_PROGRESS:
                Logger.e("视频播放进度，会通知当前播放进度、加载进度 和总体时长");
                // 播放进度, 单位是秒
                int curPosition = bundle.getInt(TXLiveConstants.EVT_PLAY_PROGRESS_MS);
                // 加载进度, 单位是秒
                int bufferPosition = bundle.getInt(TXLiveConstants.EVT_PLAYABLE_DURATION_MS);
                // 视频总长, 单位是秒
                int duration = bundle.getInt(TXLiveConstants.EVT_PLAY_DURATION_MS);
                updateProgress(curPosition, bufferPosition, duration);
                break;
            case TXLiveConstants.PLAY_EVT_PLAY_LOADING:
                Logger.e("视频播放Loading，如果能够恢复，之后会有 PLAY_EVT_PLAY_BEGIN 事件");
                llLoading.setVisibility(View.VISIBLE);
                break;
            case TXLiveConstants.PLAY_EVT_PLAY_END:
                Logger.e("视频播放结束");
                setCompletedView();
                break;
            case TXLiveConstants.PLAY_ERR_NET_DISCONNECT:
                Logger.e("网络断连,且经多次重连亦不能恢复,更多重试请自行重启播放");
                error(3, 3, "视频播放失败!");
                break;
            case TXLiveConstants.PLAY_WARNING_VIDEO_DECODE_FAIL:
                Logger.e("当前视频帧解码失败");
                // error(0, 0, "视频播放失败!");
                break;
            case TXLiveConstants.PLAY_WARNING_AUDIO_DECODE_FAIL:
                Logger.e("当前音频帧解码失败");
                // error(0, 0, "视频播放失败!");
                break;
            case TXLiveConstants.PLAY_WARNING_RECONNECT:
                Logger.e("网络断连, 已启动自动重连 (重连超过三次就直接抛送 PLAY_ERR_NET_DISCONNECT 了)");
                // error(0, 0, "视频播放失败!");
                break;
            case TXLiveConstants.PLAY_WARNING_RECV_DATA_LAG:
                Logger.e("网络来包不稳：可能是下行带宽不足，或由于主播端出流不均匀");
                // error(0, 0, "视频播放失败!");
                break;
            case TXLiveConstants.PLAY_WARNING_VIDEO_PLAY_LAG:
                Logger.e("当前视频播放出现卡顿");
                // error(0, 0, "视频播放失败!");
                break;
            case TXLiveConstants.PLAY_WARNING_HW_ACCELERATION_FAIL:
                Logger.e("硬解启动失败，采用软解");
                // error(0, 0, "视频播放失败!");
                break;
            case TXLiveConstants.PLAY_WARNING_VIDEO_DISCONTINUITY:
                Logger.e("当前视频帧不连续，可能丢帧");
                // error(0, 0, "视频播放失败!");
                break;
            case TXLiveConstants.PLAY_WARNING_DNS_FAIL:
                Logger.e("RTMP-DNS解析失败（仅播放RTMP地址时会抛送）");
                // error(0, 0, "视频播放失败!");
                break;
            case TXLiveConstants.PLAY_WARNING_SEVER_CONN_FAIL:
                Logger.e("RTMP服务器连接失败（仅播放RTMP地址时会抛送）");
                // error(0, 0, "视频播放失败!");
                break;
            case TXLiveConstants.PLAY_WARNING_SHAKE_FAIL:
                Logger.e("RTMP服务器握手失败（仅播放RTMP地址时会抛送）");
                // error(0, 0, "视频播放失败!");
                break;
        }
    }

    @Override
    public void onNetStatus(TXVodPlayer txVodPlayer, Bundle bundle) {
        // NET_STATUS_CPU_USAGE	当前瞬时CPU使用率
        // NET_STATUS_VIDEO_WIDTH	视频分辨率 - 宽
        // NET_STATUS_VIDEO_HEIGHT	视频分辨率 - 高
        // NET_STATUS_NET_SPEED	当前的网络数据接收速度
        // NET_STATUS_VIDEO_FPS	当前流媒体的视频帧率
        // NET_STATUS_VIDEO_BITRATE	当前流媒体的视频码率，单位 kbps
        // NET_STATUS_AUDIO_BITRATE	当前流媒体的音频码率，单位 kbps
        // NET_STATUS_CACHE_SIZE	缓冲区（jitterbuffer）大小，缓冲区当前长度为 0，说明离卡顿就不远了
        // NET_STATUS_SERVER_IP	连接的服务器IP
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        changeContainerViewSize(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE);
    }

    /**
     * 获取播放器对象
     */
    public TXVodPlayer getTXVodPlayer() {
        return txVodPlayer;
    }

    /**
     * 获取播放器状态
     */
    public int getPlayerState() {
        return mPlayerState;
    }

    /**
     * 设置播放监听
     */
    public void setOnPlayerListener(OnPlayerListener onPlayerListener) {
        this.onPlayerListener = onPlayerListener;
    }

    /**
     * 解注册播放监听
     */
    public void unOnPlayerListener() {
        if (onPlayerListener != null) {
            onPlayerListener = null;
        }
    }

    @Override
    public void init(int mode) {

    }

    @Override
    public void init(Activity mActivity, int playMode, String playerUrl, String previewPath, String duration) {
        if (mPlayerState > 0) {
            return;
        }

        setInitView();

        this.mPlayMode = playMode;
        switch (playMode) {
            case IVideoController.MODE_VIDEO:
                llPlayer.setVisibility(View.VISIBLE);
                tvCurrentPosition.setVisibility(View.VISIBLE);
                sbProgress.setVisibility(View.VISIBLE);
                tvTotalDuration.setVisibility(View.VISIBLE);

                tvDuration.setText(duration);
                // tvDuration.setText(formatTime(duration));
                break;
            case IVideoController.MODE_LIVE:
                llPlayer.setVisibility(View.GONE);
                tvCurrentPosition.setVisibility(View.GONE);
                sbProgress.setVisibility(View.GONE);
                tvTotalDuration.setVisibility(View.GONE);

                tvDuration.setText("--:--");
                break;
        }

        ivPreview.setImageResource(R.drawable.video_def);

        if (TextUtils.isEmpty(playerUrl)) {
            this.playerUrl = "http://player.alicdn.com/video/aliyunmedia.mp4";
        } else {
            this.playerUrl = playerUrl;
        }
    }

    @Override
    public void start() {
        Logger.e("start getPlayerState():" + getPlayerState());
        if (inspectPlayer()) {
            if (mPlayerState == 1) {
                setStartedView();
            } else if (mPlayerState == 5 && !isCanReplay) {
                setCompletedView();
            } else if (mPlayerState == 2 && mPlayMode == IVideoController.MODE_VIDEO) {
                txVodPlayer.resume();
                setStartedView();
            } else {
                isCanReplay = false;
                txVodPlayer.startPlay(playerUrl);
            }
        }
    }

    @Override
    public void start(Activity mActivity, String playUrl, String previewPath, String duration) {

    }

    @Override
    public void pause() {
        if (mPlayerState == 1) {
            if (mPlayMode == IVideoController.MODE_VIDEO) {
                txVodPlayer.pause();
            } else {
                txVodPlayer.stopPlay(false);
            }
            setPausedView();
        }
    }

    @Override
    public void autoPause() {
        mAutoPlayerState = (mPlayerState == 1);
        if (mAutoPlayerState) {
            pause();
        }
    }

    @Override
    public void resume() {
        if (inspectPlayer()) {
            if (mPlayerState == 2) {
                if (mPlayMode == IVideoController.MODE_VIDEO) {
                    txVodPlayer.resume();
                    setStartedView();
                } else {
                    isCanReplay = false;
                    txVodPlayer.startPlay(playerUrl);
                }
            }
        }
    }

    @Override
    public void autoResume() {
        if (mAutoPlayerState) {
            mAutoPlayerState = false;
            resume();
        }
    }

    @Override
    public void stop() {

    }

    @Override
    public void destroy() {
        if (txVodPlayer != null) {
            txVodPlayer.stopPlay(true);
            txVodPlayer = null;
        }
        setInitView();
    }

    @Override
    public void seekTo(int ms) {
        txVodPlayer.seek(ms);
    }

    @Override
    public void setCanReplay(boolean isCanReplay) {
        this.isCanReplay = isCanReplay;
    }

    @Override
    public void error(int causeCode, int sceneCode, String message) {
        setErrorView();

        tvErrorMsg.setText(message);
        tvErrorBtn.setTag(causeCode);
        tvErrorBtn.setVisibility(View.VISIBLE);
        switch (causeCode) {
            case 1:
                tvErrorBtn.setVisibility(View.INVISIBLE);
                break;
            case 2:
                tvErrorBtn.setVisibility(View.INVISIBLE);
                break;
            case 3:
                tvErrorBtn.setText("联网重试");
                break;
            case 4:
                tvErrorBtn.setText("继续播放");
                break;
            case 4019:
                tvErrorBtn.setVisibility(View.INVISIBLE);
                break;
            default:
                tvErrorBtn.setText("点击重试");
                break;
        }

        if (onPlayerListener != null) {
            onPlayerListener.onError(causeCode, sceneCode, message);
        }
    }

    @Override
    public void showToolsView() {
        showToolsView(5000);
    }

    @Override
    public void showToolsView(int time) {
        startCountDown(time);
        ivPlayer.setVisibility(View.VISIBLE);
        llTools.setVisibility(View.VISIBLE);
        pbProgress.setVisibility(View.GONE);
        if (onPlayerListener != null) {
            onPlayerListener.showToolsView();
        }
    }

    @Override
    public void hideToolsView() {
        ivPlayer.setVisibility(View.GONE);
        llTools.setVisibility(View.GONE);
        pbProgress.setVisibility(View.VISIBLE);
        if (onPlayerListener != null) {
            onPlayerListener.hideToolsView();
        }
    }

    @Override
    public void updateProgress(int curPosition, int bufferPosition, int duration) {
        Logger.d("duration = " + duration + " , bufferPosition = " + bufferPosition + " , curPosition = " + curPosition);

        tvCurrentPosition.setText(PlayerUtils.formatTime(curPosition));
        tvTotalDuration.setText(PlayerUtils.formatTime(duration));

        sbProgress.setMax(duration);
        sbProgress.setSecondaryProgress(bufferPosition);
        sbProgress.setProgress(curPosition);

        pbProgress.setMax(duration);
        pbProgress.setSecondaryProgress(bufferPosition);
        pbProgress.setProgress(curPosition);

        if (onPlayerListener != null) {
            onPlayerListener.updateProgress(curPosition, bufferPosition, duration);
        }
    }

    @Override
    public void changedConfiguration() {
        int screenOrientation = ((Activity) mContext).getRequestedOrientation();
        if (screenOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            ((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            ((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    /**
     * 检查播放器状态
     */
    @Override
    public boolean inspectPlayer() {
        boolean isCanPlay;
        if (TextUtils.isEmpty(playerUrl)) {
            error(1, 1, "当前视频地址无效!");
            isCanPlay = false;
        } else if (txVodPlayer == null) {
            initVodPlayer();
            error(2, 2, "播放器异常,请稍后重试!");
            isCanPlay = false;
        } else {
            if (!NetUtils.isConnected()) {
                if (mPlayerState == 1) {
                    txVodPlayer.pause();

                    error(3, 3, "网络断开,请联网后重试.");
                }
                isCanPlay = false;
            } else {
                // 获取当前网络类型
                int netType = NetUtils.getNetworkType();
                // 获取是否可使用移动网络
                boolean useTrafficPlay = PlayerUtils.getUseTrafficPlay();
                if (netType != 1 && !useTrafficPlay) {
                    if (mPlayerState == 1) {
                        txVodPlayer.pause();

                        error(4, 4, "当前使用数据流量,是否继续播放?");
                    }
                    isCanPlay = false;
                } else {
                    // ivPlayer.setImageResource(R.drawable.play_white);
                    isCanPlay = true;
                }
            }
        }
        return isCanPlay;
    }

    @Override
    public boolean isCanPlayer() {
        return false;
    }

    private void startCountDown(int time) {
        stopCountDown();
        mCountDownTimer = new CountDownTimer(time, 1000) {
            @Override
            public void onTick(long l) {
            }

            @Override
            public void onFinish() {
                hideToolsView();
            }
        };
        mCountDownTimer.start();
    }

    private void stopCountDown() {
        if (mCountDownTimer != null) {
            mCountDownTimer.onFinish();
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

    private void setInitView() {
        stopCountDown();

        ivPlayer.setImageResource(R.drawable.play_white);

        ivPreview.setVisibility(View.VISIBLE);
        ivPlayer.setVisibility(View.VISIBLE);
        tvDuration.setVisibility(View.VISIBLE);

        llLoading.setVisibility(View.GONE);

        tvReset.setVisibility(View.GONE);
        llShare.setVisibility(View.GONE);

        llErrorView.setVisibility(View.GONE);

        llTools.setVisibility(View.GONE);
        pbProgress.setVisibility(GONE);

        if (onPlayerListener != null) {
            onPlayerListener.onInit();
        }
    }

    private void setLoadingView() {
        stopCountDown();

        mPlayerState = 0;

        ivPlayer.setImageResource(R.drawable.stop_white);

        ivPreview.setVisibility(View.GONE);
        ivPlayer.setVisibility(View.GONE);
        tvDuration.setVisibility(View.GONE);

        llLoading.setVisibility(View.VISIBLE);

        tvReset.setVisibility(View.GONE);
        llShare.setVisibility(View.GONE);

        llErrorView.setVisibility(View.GONE);

        llTools.setVisibility(View.GONE);
        pbProgress.setVisibility(GONE);

        if (onPlayerListener != null) {
            onPlayerListener.onPrepared();
        }
    }

    private void setStartedView() {
        stopCountDown();

        mPlayerState = 1;

        ivPlayer.setImageResource(R.drawable.stop_white);

        ivPreview.setVisibility(View.GONE);
        ivPlayer.setVisibility(View.GONE);
        tvDuration.setVisibility(View.GONE);

        llLoading.setVisibility(View.GONE);

        tvReset.setVisibility(View.GONE);
        llShare.setVisibility(View.GONE);

        llErrorView.setVisibility(View.GONE);

        llTools.setVisibility(View.GONE);
        pbProgress.setVisibility(VISIBLE);

        if (onPlayerListener != null) {
            onPlayerListener.onStarted();
        }
    }

    private void setPausedView() {
        stopCountDown();

        mPlayerState = 2;

        ivPlayer.setImageResource(R.drawable.play_white);

        ivPreview.setVisibility(View.GONE);
        ivPlayer.setVisibility(View.VISIBLE);
        tvDuration.setVisibility(View.GONE);

        llLoading.setVisibility(View.GONE);

        tvReset.setVisibility(View.GONE);
        llShare.setVisibility(View.GONE);

        llErrorView.setVisibility(View.GONE);

        llTools.setVisibility(View.VISIBLE);
        pbProgress.setVisibility(GONE);

        if (onPlayerListener != null) {
            onPlayerListener.onPaused();
        }
    }

    private void setCompletedView() {
        stopCountDown();

        mPlayerState = 5;

        ivPlayer.setImageResource(R.drawable.play_white);

        ivPreview.setVisibility(View.VISIBLE);
        ivPlayer.setVisibility(View.GONE);
        tvDuration.setVisibility(View.GONE);

        llLoading.setVisibility(View.GONE);

        tvReset.setVisibility(View.VISIBLE);
        llShare.setVisibility(View.VISIBLE);

        llErrorView.setVisibility(View.GONE);

        llTools.setVisibility(View.GONE);
        pbProgress.setVisibility(GONE);

        if (onPlayerListener != null) {
            onPlayerListener.onCompletion();
        }
    }

    private void setErrorView() {
        stopCountDown();

        mPlayerState = 4;

        ivPlayer.setImageResource(R.drawable.play_white);

        ivPreview.setVisibility(View.VISIBLE);
        ivPlayer.setVisibility(View.GONE);
        tvDuration.setVisibility(View.GONE);

        llLoading.setVisibility(View.GONE);

        tvReset.setVisibility(View.GONE);
        llShare.setVisibility(View.GONE);

        llErrorView.setVisibility(View.VISIBLE);

        llTools.setVisibility(View.GONE);
        pbProgress.setVisibility(GONE);
    }

}
